import json
import os
import shutil
def json2txt(path_json:str, path_save_txt:str,image_path:str,num_points:int):
    '''
    path_json:json文件夹路径
    path_save:保存到的txt
    image_path:图片文件夹路径
    num_points:过滤<num_points那些点

    如果某个json文件里的关键点数量 > num_points 则强行删除json后面多余的点
    如果某个json文件里的关键点数量 < num_points 则跳过该json文件
    '''
    list_json = os.listdir(path_json)
    with open(os.path.join(path_save_txt,'train.txt'), 'w') as fw:
        for index, json_name in enumerate(list_json):
            print("index=%d,name=%s" % (index, json_name))
            path_full_json = os.path.join(path_json, json_name)

            with open(path_full_json) as f:
                json_dict = json.load(f)
                rotate = json_dict['rotate']
                objects = json_dict['objects']

                if len(objects) < num_points:
                    continue
                file_prefixName = ''.join(json_name.split(".")[:-1])        #json文件名的前缀
                image_full_path = os.path.join(image_path,file_prefixName+".jpg")       #对应的image完整路径
                if not os.path.exists(image_full_path):     #如果不能根据json文件名去找到对应的image文件名，则跳过
                    continue
                else:
                    fw.write(image_full_path+" ")

                    if len(objects) > num_points:
                        for i in range(len(objects)-num_points):
                            objects.pop()

                    for index,points in enumerate(objects):
                        label = points['label']
                        point = points['point']
                        item = str(int(point[0]))+","+str(int(point[1]))+","+str(label)
                        if index != len(objects)-1:
                            fw.write(item)
                            fw.write(" ")
                        else:
                            fw.write(item)
                            fw.write("\n")


def create_dir(path):
    '''
    创建path的文件夹，如果该文件夹存在，则忽略。
    '''
    if not os.path.isdir(path):
        os.makedirs(path)
        print(f"Maked a dir:{path}")

def move_and_merge_keypointDatsets(origin_dir:str, save_dir:str):
    json_path = os.path.join(save_dir,'json')
    image_path = os.path.join(save_dir,'images')
    labelimg_path = os.path.join(save_dir,'标签图片')
    xml_path = os.path.join(save_dir,'xml')

    create_dir(json_path)
    create_dir(image_path)
    create_dir(labelimg_path)
    create_dir(xml_path)

    for sub_dir in os.listdir(origin_dir):
        sub_dir_path = os.path.join(origin_dir,sub_dir,'result')
        for k in os.listdir(sub_dir_path):
            subsub_dir_path = os.path.join(sub_dir_path,k)
            for dirs in os.listdir(subsub_dir_path):
                if dirs == 'json':
                    for i in os.listdir(os.path.join(subsub_dir_path,dirs)):
                        file_path = os.path.join(subsub_dir_path,dirs,i)
                        shutil.move(file_path,json_path)
                elif dirs == 'mark':
                    for i in os.listdir(os.path.join(subsub_dir_path,dirs)):
                        file_path = os.path.join(subsub_dir_path,dirs,i)
                        shutil.move(file_path,image_path)
                elif dirs == 'xml':
                    for i in os.listdir(os.path.join(subsub_dir_path, dirs)):
                        file_path = os.path.join(subsub_dir_path, dirs, i)
                        shutil.move(file_path, xml_path)
                elif dirs == 'mark1':
                    for i in os.listdir(os.path.join(subsub_dir_path, dirs)):
                        file_path = os.path.join(subsub_dir_path, dirs, i)
                        shutil.move(file_path, labelimg_path)

def delete_posix(path:str,correct_postfix:str,error_postfix:list):
    '''
    path:文件夹路径
    correct_postfix:正确的文件后缀名,只会对以这种文件进行处理
    error_postfix:不要的文件后缀名
    '''
    all_fileNames = os.listdir(path)
    for fileName in all_fileNames:
        if fileName.endswith(correct_postfix):
            file_prefix = fileName[:-(len(correct_postfix)+1)]

            file_prefix_postfix = file_prefix.split(".")[-1]
            if file_prefix_postfix in error_postfix:
                new_file_name = "".join(file_prefix.split(".")[:-1])
                new_full_path = os.path.join(path,new_file_name)+"."+correct_postfix
                old_full_path = os.path.join(path,fileName)
                os.rename(old_full_path,new_full_path)

if __name__=="__main__":
    '''
    ==================================================================================================
    flag = 0    将json转换成txt，多个json对应一个txt，前提：保证一个json只对应一辆车的关键点信息，json文件格式:
                {"objects":[{"label":"1","point":[166.0,89.0]},{"label":"0","point":[32.5,240.0]}],"rotate":0}
                生成的txt的每行格式：'对应图片路径' 405.0,453.0,0 75.0,448.0,0 367.0,176.0,1 577.0,176.0,1 457.0,145.0,0 194.0,143.0,0
                注意：经常发现json文件夹下的文件名不规范，比如 XXX.jpg.json，而image下的文件名为xxx.jpg。最好执行一下flog=2的函数，否则会导致生成的txt为空。
    --------------------------------------------------------------------------------------------------
    flag = 1    将原先的多个文件夹的images,json，xml文件，合并到一起，由于文件夹过多，因此用代码执行。使用场景较少
    --------------------------------------------------------------------------------------------------
    flag = 2    删除多余的文件名
                例如原文件名为0x4j340.jpg.json，更改为0x4j340.json
    ==================================================================================================
    '''
    flag = 0

    if flag == 0:
        path_json = '/media/jiji/3b75ab20-92d3-4be6-81c2-4e1798e2fe16/公司数据/车辆关键点/数据集/json'          #原始json目录
        path_save_txt = '/media/jiji/3b75ab20-92d3-4be6-81c2-4e1798e2fe16/公司数据/车辆关键点/数据集'      #保存txt目录
        image_path = '/media/jiji/3b75ab20-92d3-4be6-81c2-4e1798e2fe16/公司数据/车辆关键点/数据集/images'         #图片路径
        json2txt(path_json,path_save_txt,image_path,16) #数字意味着保留前n个坐标
    elif flag == 1:
        save_dir = '/media/jiji/3b75ab20-92d3-4be6-81c2-4e1798e2fe16/公司数据/车辆关键点/新建文件夹'  #目标路径
        origin_dir = '/media/jiji/3b75ab20-92d3-4be6-81c2-4e1798e2fe16/公司数据/车辆关键点/car_key_point'#原始路径
        move_and_merge_keypointDatsets(origin_dir,save_dir)
    elif flag == 2:
        path = "/media/jiji/3b75ab20-92d3-4be6-81c2-4e1798e2fe16/公司数据/车辆关键点/4月13新数据/json(副本)"
        delete_posix(path,"json",["jpg","png","jpeg"])
    else:
        pass